import request from "../util/request";
import adminListView from "$v/adminList";
import {
    addAdminRequest,
    adminListRequest
} from "$a/admin"
const showAdminList = async (res) => {
    let adminListResult = null
    try {
        adminListResult = await adminListRequest({})
    } catch (e) {
        alert('获取管理员列表异常' + e.message)
    }
    res.render(adminListView({
        adminList: adminListResult
    }))
    // console.log(adminListResult);
}
export default async (req, res) => {
    //因为渲染视图被封装程函数了，所以得让下面的代码异步执行
    await showAdminList(res)

    const oSaveAdminBtn = document.getElementById('saveAdminBtn');
    document.onclick = async function (e) {
        if (e.target.id==='saveAdminBtn') {
            const adminValue = document.adminForm.adminName.value.trim();
        const passwordValue = document.adminForm.password.value.trim();
        const rePasswordValue = document.adminForm.rePassword.value.trim();
        if (!adminValue || !passwordValue || !rePasswordValue) {
            return alert('输入框不能为空')
        }
        if (passwordValue !== rePasswordValue) {
            return alert('密码不一致，请重新输入')
        }
        try {
            await addAdminRequest({
                adminName: adminValue,
                password: passwordValue,
                regTime: new Date().toLocaleString()
            })
            showAdminList(res)
            document.adminForm.reset()
            document.getElementById("closeAdd").click()
        } catch (e) {
            document.adminForm.reset()
            alert("添加失败" + e.message)
          
        }
    }
    
    }
}